package com.lijz.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.GZIPInputStream;
import java.util.zip.InflaterInputStream;

public class HttpUtil {
	public static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);

	public static Map<String, Cookie> getCookies(HttpServletRequest request) {
		Cookie[] cookies = request.getCookies();
		Map<String, Cookie> map = new HashMap<String, Cookie>();
		if (cookies != null && cookies.length > 0) {
			for (int i = 0; i < cookies.length; i++) {
				map.put(cookies[i].getName(), cookies[i]);
			}
		}
		return map;
	}

	public static Map<String, String> getHeaders(HttpServletRequest request) {
		Map<String, String> map = new HashMap<String, String>();
		Enumeration<String> names = request.getHeaderNames();
		while (names.hasMoreElements()) {
			String name = names.nextElement();
			map.put(name, request.getHeader(name));
		}
		return map;
	}

	/**
	 * 从http请求中读取post数据
	 *
	 * @param req
	 * @return
	 * @throws Exception
	 */
	public static String readRequestBody(HttpServletRequest req) throws Exception {
		String ParamStr;
		int alg = 0;
		ByteArrayOutputStream bsReceiveStream = readDataFromStream(req.getInputStream());
		if (bsReceiveStream != null) {

			ByteArrayInputStream bsPreDecompressStream = new ByteArrayInputStream(bsReceiveStream.toByteArray());

			String encode = req.getHeader("Content-Encoding"); // gzip|deflate|inflate
			if (encode != null) {

				if (encode.indexOf("deflate") >= 0 || encode.indexOf("inflate") >= 0) {
					// uncompress using inflate
					alg = 1;
				} else if (encode.indexOf("gzip") >= 0) {
					alg = 2;
					// uncompress using gzip
				}

			}
			ByteArrayOutputStream bsDeCompressStream;

			if (alg > 0) {
				bsDeCompressStream = new ByteArrayOutputStream();
				if (bsReceiveStream.size() > 0)
					decompress(bsPreDecompressStream, bsDeCompressStream, alg);
				else {
					bsDeCompressStream.close();
					bsDeCompressStream = bsReceiveStream;
				}

			} else
				bsDeCompressStream = bsReceiveStream;

			if (bsDeCompressStream.size() > 0) {
				ParamStr = new String(bsDeCompressStream.toByteArray(), "UTF-8");
			} else
				ParamStr = "";

			bsReceiveStream.close();
			return ParamStr;
		} else {
			return "";
		}
	}

	/*
	 * 从流中读取数据
	 */
	public static ByteArrayOutputStream readDataFromStream(InputStream in)
			throws IOException {
		ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
		int MAXLEN = 1024 * 10;
		byte[] cBuffer = new byte[MAXLEN];
		int bytes = 0;
		try {
			while ((bytes = in.read(cBuffer)) != -1) {
				byteStream.write(cBuffer, 0, bytes);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			byteStream.close();
		}
		return byteStream;
	}

	public static void decompress(InputStream is, OutputStream os, int alg) throws Exception {
		InflaterInputStream gis = null;
		if (alg == 2)
			gis = new GZIPInputStream(is);
		if (alg == 1)
			gis = new InflaterInputStream(is);

		int count;
		byte data[] = new byte[1024 * 1024];
		while ((count = gis.read(data, 0, 1024 * 1024)) != -1) {
			os.write(data, 0, count);
		}

		gis.close();
	}
}
